#!/bin/bash

CONSOLE_LINE_BREAK="//////////////////////////////////////////////////////////////////////////"

echo ""
echo $CONSOLE_LINE_BREAK
echo "Copying shared backend code folder..."
echo ""

DIR=$(dirname $0)

SHARED_BACKEND_CODE_SOURCE_DIR=$DIR/../shared_backend_code_source/

function prepend_warning_to_all_files_in_dir {
  # extract args from function call
  DIRECTORY_TO_ACT_ON=$1

  # find and modify all files in folder
  find $DIRECTORY_TO_ACT_ON -type f -exec sh -c '
echo - Adding warning header to $0
cat << EOF > $0
////////////////////////////////////////////////////////////
// WARNING: AUTO GENERATED FILE
//
// DO NOT EDIT THIS FILE DIRECTLY
//
// Original source file exists in /shared_backend_code_source
// at the root of this repository
//
// Codegen command: bash commands/generate_shared_code.sh
//
////////////////////////////////////////////////////////////

$(cat $0)
EOF
' {} \;
}

function copy_shared_code {
  DESTINATION_DIR=$1

  echo "Removing existing generated folder..."
  rm -rf $DESTINATION_DIR

  echo "Copying all files to destination folder..."
  # Copy to destination folder
  cp -r $SHARED_BACKEND_CODE_SOURCE_DIR $DESTINATION_DIR

  prepend_warning_to_all_files_in_dir $DESTINATION_DIR
}

###############################################################
# Start Rairnode
RAIRNODE_DESTINATION_DIR=$DIR/../rairnode/bin/shared_backend_code_generated/
copy_shared_code $RAIRNODE_DESTINATION_DIR
# End Rairnode
###############################################################

###############################################################
# Start Blockchain network
BLOCKCHAIN_NETWORK_DESTINATION_DIR=$DIR/../blockchain-networks-service/bin/shared_backend_code_generated/
copy_shared_code $BLOCKCHAIN_NETWORK_DESTINATION_DIR
# End Blockchain network
###############################################################

###############################################################
# Start Media service
RAIRNODE_DESTINATION_DIR=$DIR/../media-service/bin/shared_backend_code_generated/
copy_shared_code $RAIRNODE_DESTINATION_DIR
# End Media service
###############################################################

# Copy this pattern for each shared code destination desitnation

echo ""
echo "Code generation complete!"
echo $CONSOLE_LINE_BREAK
echo ""
